/**
 * 流程管理-流程管理模板
 */
import React, { useEffect } from 'react';
import { Card, Empty, Row, Spin } from 'antd';
import { connect } from 'umi';

import PageHeaderWrapper from '@/components/PageHeaderWrapper/index';
import updateQuery from '@/utils/formValuesToQuery';
import withClearState from '@/utils/withClearState';
import { withRoutePage } from '@/utils/enhanceUtils';
import TreeSelectPro from '@/components/TreeSelectPro/TreeSelectPro';
import useTreeSelectData from '@/hooks/useTreeSelectData';
import { TemplateItem } from '../../components';

const getCompanyId = (user, query) => {
    const userCompanyId = user ? user.companyId : '';
    return query.companyId || userCompanyId;
};

const TemplateList = props => {
    const { loading, dispatch, match, location, templateManage, user } = props;
    const { query } = location;
    const { templateList } = templateManage;
    const [companyTreeData, companyTreeLoading] = useTreeSelectData('company');

    /* 获取当前用户所在公司 ID */
    const companyId = getCompanyId(user, query);

    const updateQueryFunc = obj => {
        updateQuery(match.path, { ...obj });
    };

    const handleCompanyChange = value => {
        updateQueryFunc({ companyId: value });
    };

    const fetchData = async () => {
        if (!companyId) return;
        dispatch({
            type: 'templateManage/fetchList',
            payload: {
                organizationCode: companyId
            }
        });
    };

    useEffect(() => {
        fetchData();
    }, [companyId]);

    const renderList = () => {
        if (templateList.length === 0) {
            return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
        }
        return templateList.map(item => <TemplateItem {...props} data={item} key={item.category} />);
    };

    return (
        <PageHeaderWrapper>
            <Card bordered={false}>
                <Row>
                    <Row type="flex" align="middle">
                        <span>适用公司：</span>
                        <TreeSelectPro
                            showSearch
                            treeDefaultExpandAll
                            loading={companyTreeLoading}
                            treeData={companyTreeData}
                            value={companyId}
                            onChange={handleCompanyChange}
                            style={{ width: 240 }}
                            placeholder="请选择公司"
                        />
                    </Row>
                </Row>
                <Spin spinning={loading}>{renderList()}</Spin>
            </Card>
        </PageHeaderWrapper>
    );
};

const mapStateToProps = ({ templateManage, loading, user = {} }) => ({
    templateManage,
    user: user.currentUser,
    loading: loading.global
});

export default withRoutePage(connect(mapStateToProps)(withClearState('templateManage')(TemplateList)));
